package uk.ac.cam.cl.projectcharlie2010.hardwaremove;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
 
public class RS232Example {
	
	private Status status;
	
	//NOTE: Must call connect
	public RS232Example() {
		status = new Status();
	}
	
	public synchronized void sendMove(int bigArmPosition, int smallArmPosition, boolean servoUp) {
		status.waitForReady();
		status.setReady(false);
		
		String message = "DPA" + bigArmPosition +
						 "QQQDPB" + smallArmPosition + 
						 "QQQSVS" + ((servoUp) ? 1 : 0) + "QQQ";
		
		CommPortSender.send(new ProtocolImpl(null).getMessage(message));
		
	}
   
    public void connect(String portName) throws Exception {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
 
        if (portIdentifier.isCurrentlyOwned()) {
            System.out.println("Port in use!");
        } else {
            // points who owns the port and connection timeout
            SerialPort serialPort = (SerialPort) portIdentifier.open("RS232Example", 2000);
            
            // setup connection parameters
            serialPort.setSerialPortParams(
                9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
 
            // setup serial port writer
            CommPortSender.setWriterStream(serialPort.getOutputStream());
            
            // setup serial port reader
            new CommPortReceiver(serialPort.getInputStream(), status).start();
        }
    }
    
    public static void main(String[] args) throws Exception {
        
        // connects to the port which name (e.g. COM1) is in the first argument
        RS232Example g = new RS232Example();
        g.connect("COM8");
        
        // send HELO message through serial port using protocol implementation
        /*CommPortSender.send(new ProtocolImpl().getMessage("ABC1100QQQ900QQ"));
        CommPortSender.send(new ProtocolImpl().getMessage("ABC1100QQQ900QQ"));
        CommPortSender.send(new ProtocolImpl().getMessage("ABC1100QQQ900QQ"))
        */
//        Thread.sleep(5000);
//        CommPortSender.send(new ProtocolImpl(status).getMessage("DPA1000QQQDPB900QQQSVS1QQQ"));
//        Thread.sleep(10000);
//        CommPortSender.send(new ProtocolImpl().getMessage("DPA800QQQDPB900QQQSVS0QQQ"));
        /*
        CommPortSender.send(new ProtocolImpl().getMessage("ABC1100QQQ900QQ"));
        CommPortSender.send(new ProtocolImpl().getMessage("ABC1100QQQ900QQ"));
        Thread.sleep(10000);
        CommPortSender.send(new ProtocolImpl().getMessage("ABC900QQQ1100QQ"));
        CommPortSender.send(new ProtocolImpl().getMessage("ABC900QQQ1100QQ"));
        CommPortSender.send(new ProtocolImpl().getMessage("ABC900QQQ1100QQ"));*/
    }
    
    
}